package com.server.common.utils;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTHeader;
import com.server.common.constants.TokenConstant;

import java.io.UnsupportedEncodingException;

/**
 * jwt token
 *
 * @author zgr
 * @date 2023/7/17 17:36
 */
public class JwtTokenUtil<T> {

    public static String createToken(Long id, String name) throws UnsupportedEncodingException {
        String token = JWT.create()
                .setPayload("adminId", id)
                .setPayload("adminName", name)
                .setKey(TokenConstant.SECRET.getBytes("UTF-8"))
                .setExpiresAt(DateUtil.offset(DateUtil.date(), DateField.DAY_OF_MONTH, 30))
                .sign();
        return token;
    }

    public static  <T> T getPayload(String token, String fieldName) {
        JWT jwt = JWT.of(token);
        jwt.getHeader(JWTHeader.TYPE);
        return (T) jwt.getPayload(fieldName);
    }


    public static boolean verify(String token) {
        return JWT.of(token).setKey(TokenConstant.SECRET.getBytes()).verify();
    }
}
